package com.hwd.srb.rabbitmq.impl;

import com.hwd.srb.rabbitmq.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 黄伟东/Victor
 * @date 2022/3/28 10:42
 * @Description 延迟队列就是一种特殊的死信队列，一种刚投递就投递失败的队列 //TODO
 */
@Service
@Slf4j
public class RabbitServiceImpl implements RabbitService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由
     * @param obj        消息
     */
    @Override
    public void sendMessage(String exchange, String routingKey, Object obj) {
        log.info("发送消息队列..........." + obj);
        rabbitTemplate.convertAndSend(exchange, routingKey, obj);
    }

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由
     * @param obj        消息
     * @param ttl        过期时间
     */
    @Override
    public void sendDeadMessage(String exchange, String routingKey, Object obj, Long ttl) {
        log.info("发送死信消息队列..........." + obj);

        // 设置过期时间
        rabbitTemplate.convertAndSend(exchange, routingKey, obj, message -> {
            message.getMessageProperties().setExpiration(ttl.toString());// 设置消息的ttl过期时间
            return message;
        });
    }
}
